Popular Searches
Popular Course Categories
Popular Courses

Handling Exceptions Using try and catch

Handling Exceptions Using try and catch

Exception Handling and Debugging

Handling Exceptions Using try and catch in Java

Course: Core Java Training

Topic: Handling Exceptions Using try and catch

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Exception Handling in Java

Exception handling is an important feature of Java that allows developers to manage runtime problems and prevent unexpected program termination. An exception is an event that interrupts the normal flow of program execution, such as dividing an integer by zero, accessing an invalid array index, or trying to use a file that does not exist.

Java provides several keywords for exception handling, including try, catch, finally, throw, and throws. The try and catch blocks are the basic building blocks used to detect and handle exceptions.

For example, if a program divides a number by zero, Java throws an ArithmeticException. By placing the division operation inside a try block and handling the exception in a catch block, the program can display a meaningful message instead of terminating unexpectedly.

2. Learning Objectives

  • Understand the meaning and purpose of exception handling.
  • Learn the syntax and working of the try block.
  • Learn how the catch block handles exceptions.
  • Understand the flow of execution when an exception occurs.
  • Handle common exceptions such as ArithmeticException, NumberFormatException, and ArrayIndexOutOfBoundsException.
  • Use multiple catch blocks and understand their ordering.
  • Identify common mistakes and follow exception-handling best practices.

3. What Is an Exception?

An exception is an object that represents an abnormal condition encountered while a program is running. When an exceptional condition occurs, Java creates or throws an exception object. If suitable handling code exists, the exception can be caught and processed.

Consider the following example:

public class ExceptionExample {
    public static void main(String[] args) {
        int number = 10 / 0;
        System.out.println(number);
    }
}

Explanation: Integer division by zero causes an ArithmeticException. Because the exception is not handled, the program terminates before the value of number can be printed.

Important: Exception handling does not make an invalid operation valid. It allows the program to respond to the failure in a controlled manner.

4. What Is the try Block?

The try block contains code that may produce an exception. Java monitors the execution of this block. If an exception occurs, Java stops executing the remaining statements in that particular try block and looks for a compatible exception handler.

Syntax of the try Block

try {
    // Code that may cause an exception
} catch (ExceptionType exceptionVariable) {
    // Code to handle the exception
}

A try block must be followed by at least one catch block or a finally block. A try-with-resources statement is another supported form of try used for managing resources.

Example of a try Block

public class TryExample {
    public static void main(String[] args) {
        try {
            int result = 20 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("An arithmetic error occurred.");
        }

        System.out.println("Program continues.");
    }
}

Output:

Result: 10
Program continues.

Explanation: The division is valid, so no exception occurs. The statements in the try block execute normally, and the catch block is skipped.

5. What Is the catch Block?

The catch block contains instructions for handling an exception thrown from the associated try block. Its parameter specifies the exception type it can handle, and the exception variable provides access to the exception object.

Syntax of the catch Block

catch (ExceptionType exceptionVariable) {
    // Handle the exception
}

For example:

try {
    int result = 10 / 0;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide an integer by zero.");
}

Output:

Cannot divide an integer by zero.

Explanation: Java throws an ArithmeticException during the division. The matching catch block handles it, and the program continues with the statements that follow the try-catch structure.

6. How try and catch Work Together

The try and catch blocks work together to detect and handle exceptions. The try block contains potentially risky operations, while the catch block defines how the program responds when a matching exception occurs.

Execution Flow

  1. The program enters the try block.
  2. Java executes the statements in sequence.
  3. If no exception occurs, the catch block is skipped.
  4. If an exception occurs, the remaining statements in the current try block are skipped.
  5. Java searches for a compatible catch block.
  6. If a matching handler is found, its statements execute.
  7. Execution continues after the complete try-catch structure, unless another control-flow event changes the outcome.

Example Demonstrating the Execution Flow

public class TryCatchFlow {
    public static void main(String[] args) {
        System.out.println("Program started");

        try {
            System.out.println("Inside try block");
            int result = 15 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Exception handled");
        }

        System.out.println("Program ended");
    }
}

Output:

Program started
Inside try block
Exception handled
Program ended

Explanation: The statement printing the result is not executed because the division throws an exception first. The matching catch block handles the error, and execution then reaches the final print statement.

7. Handling ArithmeticException

An ArithmeticException is an unchecked exception that can occur during certain invalid arithmetic operations, such as integer division by zero.

public class ArithmeticHandling {
    public static void main(String[] args) {
        int a = 25;
        int b = 0;

        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        }

        System.out.println("Application is still running.");
    }
}

Output:

Error: Division by zero is not allowed.
Application is still running.

Key point: This example uses integer division. Floating-point division by zero behaves differently in Java and generally produces infinity or NaN rather than throwing an ArithmeticException.

8. Handling ArrayIndexOutOfBoundsException

An ArrayIndexOutOfBoundsException occurs when code accesses an array using an invalid index, such as a negative index or an index equal to or greater than the array length.

public class ArrayExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};

        try {
            System.out.println(numbers[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: The requested array index is invalid.");
        }

        System.out.println("Execution continues.");
    }
}

Output:

Error: The requested array index is invalid.
Execution continues.

Explanation: The array contains three elements, with valid indexes from 0 to 2. Accessing index 5 throws an exception, which the catch block handles.

9. Handling NumberFormatException

A NumberFormatException occurs when a string cannot be converted into the requested numeric type. For example, converting the string "hello" to an integer is invalid.

public class NumberFormatExample {
    public static void main(String[] args) {
        String input = "hello";

        try {
            int number = Integer.parseInt(input);
            System.out.println("Number: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Error: Please provide a valid integer.");
        }

        System.out.println("Program continues.");
    }
}

Output:

Error: Please provide a valid integer.
Program continues.

Explanation: The string does not represent a valid integer. Java throws a NumberFormatException, and the matching catch block displays a helpful message.

10. Using Multiple catch Blocks

A single try block can be followed by multiple catch blocks to handle different exception types separately. Java selects the first compatible handler for the exception that occurs.

Syntax

try {
    // Statements that may throw different exceptions
} catch (ArithmeticException e) {
    // Handle arithmetic exceptions
} catch (ArrayIndexOutOfBoundsException e) {
    // Handle invalid array indexes
} catch (NumberFormatException e) {
    // Handle invalid numeric strings
}

Example

public class MultipleCatchExample {
    public static void main(String[] args) {
        String input = "abc";

        try {
            int number = Integer.parseInt(input);
            int result = 100 / number;
            System.out.println("Result: " + result);
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format.");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        }

        System.out.println("Program completed.");
    }
}

Output:

Invalid number format.
Program completed.

Explanation: The string "abc" cannot be parsed as an integer, so a NumberFormatException occurs. The division statement is never reached. If the input were "0", parsing would succeed and the division would produce an ArithmeticException.

11. Order of catch Blocks

When multiple catch blocks are used, more specific exception types must appear before more general types. Otherwise, a general handler may catch an exception before a later, more specific handler can be reached, causing a compile-time error.

Incorrect example:

try {
    int result = 10 / 0;
} catch (Exception e) {
    System.out.println("General exception");
} catch (ArithmeticException e) {
    System.out.println("Arithmetic exception");
}

This code does not compile because Exception can catch an ArithmeticException, making the later catch block unreachable.

Correct example:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Arithmetic exception");
} catch (Exception e) {
    System.out.println("General exception");
}

Output:

Arithmetic exception

12. Using a General Exception Handler

A catch block can handle a broad category of exceptions by using a parent exception type such as Exception. This can be useful when a general recovery action is appropriate, but it should not replace more precise handling where different failures require different responses.

public class GeneralCatchExample {
    public static void main(String[] args) {
        try {
            int[] values = {1, 2, 3};
            System.out.println(values[10]);
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Possible output:

An error occurred: Index 10 out of bounds for length 3

The exact wording of exception messages can vary between Java versions and runtime implementations. In production applications, catch only exceptions that can be handled meaningfully, and avoid hiding unexpected failures.

13. Difference Between try and catch

Basis try Block catch Block
Purpose Contains code that may throw an exception. Handles a matching exception.
Execution Runs first. Runs only when a matching exception is thrown from the associated try block.
Parameter Does not declare an exception parameter. Declares an exception type and variable.
Number A try statement may have one or more catch blocks, or a finally block. One try statement can have multiple catch blocks.
Responsibility Encloses potentially risky operations. Defines a response to a failure.
Example int result = 10 / 0; catch (ArithmeticException e)

14. Difference Between Exception Handling and Normal Conditional Checks

Conditional statements such as if and else can prevent known invalid operations before they happen. Exception handling is useful for responding to exceptional conditions that arise during execution.

public class DivisionCheck {
    public static void main(String[] args) {
        int a = 20;
        int b = 0;

        if (b != 0) {
            System.out.println(a / b);
        } else {
            System.out.println("The divisor must not be zero.");
        }
    }
}

Output:

The divisor must not be zero.

Use validation when an invalid value can be detected in advance. Use try-catch when an operation may throw an exception that the program can handle. These techniques can complement each other.

15. Common Mistakes in try-catch

Mistake 1: Catching the Wrong Exception

If a statement throws NumberFormatException, a catch block for ArithmeticException will not handle it. Always select an exception type that matches the failure you expect.

Mistake 2: Writing Unreachable catch Blocks

Placing a parent exception type before one of its child types can make the child handler unreachable. Arrange catch blocks from specific types to general types.

Mistake 3: Using Empty catch Blocks

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // Empty block
}

An empty catch block silently hides the error and makes debugging difficult. Log the exception appropriately, show a useful message, or recover from the problem.

Mistake 4: Assuming All Exceptions Are Recoverable

Not every exception can be safely handled by continuing execution. Determine whether the application can recover and whether its state remains valid before continuing.

Mistake 5: Printing Only a Vague Error Message

Messages such as "Something went wrong" may not provide enough information for troubleshooting. Use appropriate logging and include useful context without exposing passwords, tokens, or other sensitive data.

16. Best Practices for Exception Handling

  • Place only the statements that may reasonably throw the expected exception inside a try block.
  • Catch specific exception types whenever possible.
  • Keep catch blocks focused and easy to understand.
  • Do not ignore exceptions without a valid reason.
  • Provide clear and user-friendly error messages.
  • Use a logging framework for application diagnostics when appropriate.
  • Do not expose sensitive information in exception messages shown to users.
  • Use validation to prevent common invalid inputs before processing them.
  • Preserve the original exception when wrapping or rethrowing an error.
  • Use try-with-resources for resources such as files and streams that implement AutoCloseable.

17. Real-World Example: Validating User Input

In real applications, users may enter unexpected data. The following example demonstrates how to convert a string into an integer and handle invalid input gracefully.

public class UserInputValidation {
    public static void main(String[] args) {
        String ageInput = "twenty";

        try {
            int age = Integer.parseInt(ageInput);

            if (age < 0) {
                System.out.println("Age cannot be negative.");
            } else {
                System.out.println("Age: " + age);
            }
        } catch (NumberFormatException e) {
            System.out.println("Please enter age using digits.");
        }
    }
}

Output:

Please enter age using digits.

Explanation: The input string cannot be converted into an integer, so Java throws a NumberFormatException. The catch block informs the user about the required input format. In a real application, the value might come from a form, command-line prompt, or API request.

18. Practical Exercise: Safe Division Calculator

Task: Create a Java program that divides two integers and handles division by zero using try-catch.

Requirements:

  • Create two integer variables named numerator and denominator.
  • Perform the division inside a try block.
  • Handle ArithmeticException in a catch block.
  • Print a message after the try-catch structure to demonstrate that execution continues.

Sample solution:

public class SafeDivisionCalculator {
    public static void main(String[] args) {
        int numerator = 50;
        int denominator = 0;

        try {
            int result = numerator / denominator;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Unable to divide by zero.");
        }

        System.out.println("Calculator finished.");
    }
}

Expected output:

Unable to divide by zero.
Calculator finished.

19. Interview Questions and Answers

Q1. What is exception handling in Java?

Answer: Exception handling is a mechanism for detecting and managing exceptional conditions so that a program can respond in a controlled manner.

Q2. What is the purpose of a try block?

Answer: A try block encloses statements that may throw exceptions. It allows Java to transfer control to an appropriate handler when an exception occurs.

Q3. What is the purpose of a catch block?

Answer: A catch block handles an exception of a compatible type thrown from its associated try block.

Q4. Can a try block exist without a catch block?

Answer: Yes. A try block can be followed by a finally block without a catch block. A try-with-resources statement can also be used without catch or finally.

Q5. What happens when no exception occurs inside a try block?

Answer: The try block executes normally, and its associated catch blocks are skipped.

Q6. What happens to the remaining statements in a try block after an exception occurs?

Answer: The remaining statements in that try block are skipped, and Java searches for a matching exception handler.

Q7. Can one try block have multiple catch blocks?

Answer: Yes. Multiple catch blocks can handle different exception types, provided their ordering does not make any handler unreachable.

Q8. Why should specific exceptions be caught before general exceptions?

Answer: A general exception type may also match a more specific exception. Placing the general handler first can make later specific handlers unreachable and cause a compile-time error.

Q9. What is the difference between checked and unchecked exceptions?

Answer: Checked exceptions generally must be caught or declared in the method signature. Unchecked exceptions, including subclasses of RuntimeException, do not have this compiler requirement.

Q10. Does catching an exception automatically fix the underlying problem?

Answer: No. Catching an exception allows the program to respond to it. The code must still validate data, correct the problem, retry safely, or report the failure as appropriate.

20. Quick Revision Checklist

  • try: Contains code that may throw an exception.
  • catch: Handles a matching exception from the associated try block.
  • Exception object: Provides information about the failure.
  • Uncaught exception: May terminate the current thread if it escapes its execution path.
  • Multiple catch blocks: Allow different exception types to be handled separately.
  • Catch ordering: Specific exception types must precede broader compatible types.
  • Good practice: Catch only what you can handle meaningfully and avoid silently ignoring failures.

21. Conclusion

Handling exceptions using try and catch is a fundamental skill in Java programming. The try block encloses potentially risky operations, while the catch block provides a controlled response to matching exceptions. Understanding execution flow, handling specific exception types, ordering multiple catch blocks correctly, and following good error-handling practices helps developers create more reliable applications.

Continue learning Core Java concepts through the JustAcademy Core Java Training Course. You can also register for a course demo or visit the JustAcademy website for more information.

Previous Next
whatsapp